<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  单例模式：
  只是实例化一次，每次返回的实例都是同一对象
  <button id="btn">登录</button>
  <script>
    // 单例模式实现
    /* 
    function Singleton(name) {
      this.name = name
    }

    Singleton.prototype.getName = function () {
      console.log(this.name);
    }

    Singleton.getInstance = function (name) {
      if (!this.instance) {
        this.instance = new Singleton(name)
      }
      return this.instance
    }

    var a = Singleton.getInstance('zhangsan')
    var b = Singleton.getInstance('lisi')
    console.log(a);
    console.log(b);
    console.log(a === b);
 */

    // 单例模式的应用

    // 传统模式下 点击多次会产生多个登录框 不符合要求
    // var createDiv = function () {
    //   var div = document.createElement("div");
    //   div.innerHTML = "我是登录框";
    //   div.style.display = 'none';
    //   document.body.appendChild(div)
    //   return div
    // }

    // 单例模式下只会产生一个登录框
    /* 
    var createDiv = (function () {
      var div
      return function () {
        if (!div) {
          div = document.createElement("div");
          div.innerHTML = "我是登录框";
          div.style.display = 'none';
          document.body.appendChild(div)
          return div
        }
        return div
      }
    })();
 */
    /* 
        var createIframe = (function () {
          var iframe;
          return function () {
            if (!iframe) {
              iframe = document.createElement("iframe");
              iframe.width = "500px";
              iframe.height = '500px'
              iframe.src = 'https://www.bilibili.com/'
              iframe.style.display = 'none';
              document.body.appendChild(iframe)
              return iframe;
            }
            return iframe
          }
        })();
     */

    // var btn = document.getElementById('btn')
    // btn.onclick = function () {
    //   var iframe = createIframe();
    //   iframe.style.display = 'block'
    // }

    // 封装一个getInstance函数，实现创建任意元素的单例模式

    var createDiv = function () {
      var div = document.createElement("div");
      div.innerHTML = "我是登录框";
      div.style.display = 'none';
      document.body.appendChild(div)
      return div
    }
    var getInstance = function (fn) {
      var res;
      return function () {
        return res || (res = fn.call(this, arguments))
      };
    }
    var createSingletonDiv = getInstance(createDiv)
    btn.onclick = function () {
      var div = createSingletonDiv();
      div.style.display = 'block'
    }
  </script>
</body>

</html>